import React, { Fragment } from 'react';

import { Link, withRouter } from 'react-router-dom';
import { Menu } from 'antd';

import './index.less';
import logo from '../../assets/images/icon.png';

import menuList from '../../config/menuConfig';
import { once } from '../../utils/toolKit';
import memory from '../../utils/memoryUtils';

const { SubMenu, Item } = Menu;

function hasAuth(item) {
    const {key} = item;
    let menus = [];
    let username = '';
    if (memory.user._id) {
        menus = memory.user.role.menus;
        username = memory.user.username;
    }

    if (item.children && item.children.length !== 0) {
        return item.children.some(child => hasAuth(child));
    }
    return menus.includes(key) || username === 'admin' || key === '/home';
}

function getMenuNodes(list) {
    
    return list.map(item => {
        const { key, icon, title } = item;
        if (hasAuth(item)) {
            if (item.children && item.children.length !== 0) {
                return (
                    <SubMenu key={key} icon={icon} title={title}>
                        {
                            getMenuNodes(item.children)
                        }
                    </SubMenu>
                )
            }
            return (
                <Item key={key} icon={icon}>
                    <Link to={key}>{title}</Link>
                </Item>
            )
        }
        return null;
    })
}

function defaultOpenKey(menuList, pathname) {
    for (let i = 0, len = menuList.length; i < len; i++) {
        const item = menuList[i];

        if (pathname === (item.key)) return pathname;
        if (pathname.startsWith(item.key)) return pathname.slice(0, pathname.lastIndexOf('/'))

        if (item.children && item.children.length !== 0) {
            if (defaultOpenKey(item.children, pathname)) return item.key;
        }
    }
    return null;
}

function getSelectedKey(pathname) {
    if (pathname && pathname.startsWith('/product')) {
        return '/product';
    }
    return pathname;
}

const getDefaultOpenKey = once(defaultOpenKey);

/**
 * 左侧导航栏组件
 */
function LeftNav(props) {

    const { pathname } = props.location;

    return (
        <Fragment>
            <Link to="/home" className="left-nav-header">
                <img src={logo} alt="logo" />
                <h2>GULI-Mall</h2>
            </Link>

            <Menu mode="inline" theme="dark" defaultOpenKeys={[getDefaultOpenKey(menuList, pathname)]} selectedKeys={[getSelectedKey(pathname)]}>
                {
                    getMenuNodes(menuList)
                }
            </Menu>
        </Fragment>
    )
}

export default withRouter(LeftNav);
